import React, { createContext, useState, useEffect, useContext, ReactNode } from 'react';
import { auth } from '../services/api';

// 用户接口
export interface User {
  id: number;
  username: string;
  email: string;
  role: string;
  created_at: string;
}

// 上下文接口
interface UserContextType {
  currentUser: User | null;
  isLoading: boolean;
  error: string | null;
  refreshUser: () => Promise<void>;
  isAdmin: () => boolean;
}

// 创建上下文
const UserContext = createContext<UserContextType | undefined>(undefined);

// 上下文提供者属性
interface UserProviderProps {
  children: ReactNode;
}

// 上下文提供者组件
export const UserProvider: React.FC<UserProviderProps> = ({ children }) => {
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    setIsLoading(true);
    setError(null);
    
    try {
      const token = localStorage.getItem('token');
      if (!token) {
        setCurrentUser(null);
        setIsLoading(false);
        return;
      }
      
      const response = await auth.getCurrentUser();
      setCurrentUser(response.data);
    } catch (error: any) {
      console.error('获取用户信息失败:', error);
      setError(error.response?.data?.error || '获取用户信息失败');
      // 如果令牌无效，清除本地存储
      if (error.response?.status === 401) {
        localStorage.removeItem('token');
        setCurrentUser(null);
      }
    } finally {
      setIsLoading(false);
    }
  };

  // 提供刷新用户信息的方法
  const refreshUser = async () => {
    await fetchCurrentUser();
  };

  // 检查是否为管理员
  const isAdmin = () => {
    return currentUser?.role === 'admin';
  };

  // 首次加载时获取用户信息
  useEffect(() => {
    fetchCurrentUser();
  }, []);

  const value = {
    currentUser,
    isLoading,
    error,
    refreshUser,
    isAdmin
  };

  return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
};

// 自定义钩子，便于在组件中使用上下文
export const useUser = (): UserContextType => {
  const context = useContext(UserContext);
  
  if (context === undefined) {
    throw new Error('useUser must be used within a UserProvider');
  }
  
  return context;
}; 